import React, {Component} from 'react'
import {Button, Col, Icon,Modal, Popconfirm, Row, message} from 'antd'
import {TwsBelongTask} from 'tws-antd'
import {connect} from 'react-redux'
import '../less/index.less'
import {withRouter} from 'react-router-dom'
import MultipleChoiceQuiz from './common/multiple-choice-quiz'
import SingleChoiceQuiz from './common/single-choice-quiz'
import BasicBlankQuiz from './common/basic-blank-quiz'
import EditStatusBox from './common/edit-status-box'
import * as taskActions from '../actions/task'
import * as assignment from '../actions/assignment'
import {studentGetSectionComments} from '../actions/comment'
import CommentBox from './common/comment-box'
import AssignmentSupplementaryBox from './common/assignment-supplementary-box'
import {FormattedMessage} from 'react-intl'
import {convertContent, getLangFromLocalStorage} from '../constant/lang-util'
import QuizSuggestionBox from "./common/quiz-suggestion-box";
import {getAssignmentDuration, startAssignment} from "../actions/assignment";

class AssignmentPageBody extends Component {
  constructor(props) {
    super(props)
    this.state = {
      assignmentId: 1,
      programId: 1,
      taskId: 1,
      answers: [],
      disable: false
    }
  }

  loadData = () => {
    const {assignmentId, taskId} = this.state
    this.props.getTaskInfo(taskId)
    this.props.getBasicQuizAssignment(assignmentId)
    this.props.getReviewQuiz(assignmentId)
    this.props.getComments(assignmentId, assignmentId)
  }

  showStartModal = () => {
    Modal.info({
      title: convertContent('确定开始答题？'),
      okText: convertContent('确定'),
      onOk: () => {
        this.startAssignment()
        this.loadData()
      },
    })
  }

  startAssignment = () => {
    const {taskId, assignmentId} = this.state
    const {user} = this.props
    this.props.startAssignment(user.id, taskId, assignmentId)
  }

  componentDidMount() {
    const {programId, taskId, assignmentId} = this.props.match.params
    this.setState({
      assignmentId,
      taskId,
      programId
    }, () => {
      this.props.getAssignmentDuration(taskId, assignmentId, (assignmentDuration) => {
        if (assignmentDuration.id) {
          this.loadData()
        } else {
          this.showStartModal()
        }
      })
    })
  }

  modifyAnswer(quiz, answer) {
    const {answers} = this.state
    const index = answers.findIndex(item => item.quizId === quiz.id)
    if (index !== -1) {
      answers[index].userAnswer = answer
    } else {
      answers.push({quizId: quiz.id, userAnswer: answer})
    }

    this.setState({
      answers
    })
  }

  finish = () => {
    const {answers} = this.state
    const {assignmentQuizzes} = this.props
    const {basicQuizzes} = assignmentQuizzes
    return answers.length === basicQuizzes.length
  }

  submitBasicQuiz() {
    const {answers, assignmentId} = this.state
    if (this.finish()) {
      this.props.submitBasicQuizAnswer(answers, assignmentId);
    } else {
      message.warning(convertContent('还有题目未完成'))
    }
  }

  render() {
    const {assignmentQuizzes, comments, user, settings} = this.props
    const {basicQuizzes, reviewQuiz} = assignmentQuizzes
    const {task} = this.props.taskInfo
    const {studentHomeUrl} = this.props.settings
    const {programId, taskId, assignmentId} = this.state
    const assignments = task.assignments || []
    const currentAssignment = assignments.find(assignment => assignment.id === parseInt(this.state.assignmentId)) || {}

    const quizMap = {
      'SINGLE_CHOICE': SingleChoiceQuiz,
      'MULTIPLE_CHOICE': MultipleChoiceQuiz,
      'BASIC_BLANK_QUIZ': BasicBlankQuiz
    }

    const lang = getLangFromLocalStorage()

    return <div>
      <div>
        <Row>
          <Col xs={24} sm={4} md={7} lg={8} xl={8}>
            <h2>{currentAssignment[`title_${lang}`] || currentAssignment.title}</h2>
          </Col>
          <Col xs={24} sm={10} md={7} lg={6} xl={6} offset={10}>
            <EditStatusBox reviewQuiz={reviewQuiz} disable/>
          </Col>
        </Row>
      </div>

      <div className='margin-t-3'>
        <h3><FormattedMessage id={'作业内容'}/></h3>
        {
          reviewQuiz.id
            ? <span className='submit-time-box'>
              <Icon type='clock-circle'/>
              {reviewQuiz.createTime}
            </span>
            : ''
        }
        <div className='margin-t-2 '>
          <div style={{background: 'white'}}/>
          {
            basicQuizzes.map((quiz, index) => {
              const QuizComponent = quizMap[quiz.type]
              return <div>
                <QuizComponent key={index} index={index} modifyAnswer={this.modifyAnswer.bind(this)} quiz={quiz}/>
                <QuizSuggestionBox
                  settings={settings}
                  quiz={quiz}
                  submit={this.props.submitQuizSuggestion}
                />
              </div>
            })
          }

          {
            reviewQuiz.id
              ? ''
              : <Popconfirm title={<FormattedMessage id='确定提交吗'/>}
                            onConfirm={this.submitBasicQuiz.bind(this, this.state.answers)} okText='Yes'
                            cancelText='No'>
                <Button className='margin-t-2 margin-b-3' type='primary'><FormattedMessage id='提交'/></Button>
              </Popconfirm>

          }
        </div>
      </div>
      <TwsBelongTask title={<FormattedMessage id={'所属任务卡'}/>}>
        <a href={`${studentHomeUrl}/program/` + this.state.programId + '/task/' + this.state.taskId}>
          <Icon type='arrow-left'/>
          {task[`title_${lang}`] || task.title}
        </a>
      </TwsBelongTask>
      {reviewQuiz.id
        ? <AssignmentSupplementaryBox
          submitSupplementary={this.props.submitSupplementary}
          reviewQuizId={reviewQuiz.id}
          assignmentId={this.state.assignmentId}
          reviewQuiz={reviewQuiz}/> : ''}

      <CommentBox
        user={user}
        studentId={user.id}
        programId={programId}
        taskId={taskId}
        suggestions={comments}
        quizId={assignmentId}
        assignmentId={assignmentId}/>
    </div>
  }
}

const mapStateToProps = state => ({
  taskInfo: state.taskInfo,
  assignmentQuizzes: state.assignment,
  comments: state.comments,
  user: state.user,
  settings: state.settings
})
const mapDispatchToProps = dispatch => ({
  getTaskInfo: (taskId) => dispatch(taskActions.getTaskInfo(taskId)),
  getBasicQuizAssignment: (assignmentId) => dispatch(assignment.getBasicQuizAssignment(assignmentId)),
  getReviewQuiz: (assignmentId) => dispatch(assignment.getReviewQuiz(assignmentId)),
  submitBasicQuizAnswer: (answers, assignmentId) => dispatch(assignment.submitBasicQuizAnswer(answers, assignmentId)),
  submitSupplementary: (id, supplement, assignmentId) => dispatch(assignment.submitSupplementary(id, supplement, assignmentId)),
  submitQuizSuggestion: (quizSuggestion, callback) => dispatch(assignment.submitQuizSuggestion(quizSuggestion, callback)),
  getComments: (assignmentId, quizId) => dispatch(studentGetSectionComments(assignmentId, quizId)),
  getAssignmentDuration: (taskId, assignmentId, callback) => dispatch(getAssignmentDuration(taskId, assignmentId, callback)),
  startAssignment: (userId, taskId, assignmentId) => dispatch(startAssignment(userId, taskId, assignmentId)),
})

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(AssignmentPageBody))
